<?php

namespace business\elasticsearch\repositories;

use business\elasticsearch\models\BigDataSupplierModel;
use business\elasticsearch\types\BigDataSupplierMapConfigType;
use yii\elasticsearch\Query;

class BigdataSupplierRepository
{
    /**
     * 创建索引
     * @return mixed
     */
    public function createIndex()
    {
        return BigDataSupplierModel::getDb()
            ->createCommand()
            ->createIndex(
                BigDataSupplierModel::index(),
                [
                    'settings' => [
                        'index' => [
                            'number_of_shards' => 5,
                            'number_of_replicas' => 1,
                            'analysis.analyzer.default.type' => 'ik_max_word',
                        ],
                    ],
                    'mappings' => [
                        BigDataSupplierModel::type() => BigDataSupplierMapConfigType::mapConfig()
                    ]
                ]
            );
    }

    /**
     * 索引是否存在
     * @return mixed
     */
    public function existsIndex()
    {
        return BigDataSupplierModel::getDb()
            ->createCommand()
            ->indexExists(BigDataSupplierModel::index());
    }

    /**
     * 保存记录
     * @param array $data
     * @param int $id
     * @return array|mixed
     */
    public function saveRecord($data = [], $id = 0)
    {
        if (!empty($data)) {
            return BigDataSupplierModel::getDb()
                ->createCommand()
                ->insert(
                    BigDataSupplierModel::index()
                    , BigDataSupplierModel::type()
                    , $data
                    , $id
                );
        }

        return [];
    }

    /**
     * 更新记录
     * @param $id
     * @param array $data
     * @return mixed
     */
    public function updateRecord($id, $data = [])
    {
        return BigDataSupplierModel::getDb()
            ->createCommand()
            ->update(
                BigDataSupplierModel::index()
                , BigDataSupplierModel::type()
                , $id
                , $data
            );
    }

    /**
     * 删除记录
     * @param $id
     * @return mixed
     */
    public function deleteRecord($id)
    {
        if (!empty($id)) {
            return BigDataSupplierModel::getDb()
                ->createCommand()
                ->delete(
                    BigDataSupplierModel::index()
                    , BigDataSupplierModel::type()
                    , $id
                );
        }
        return true;
    }

}
